package com.hsy.bibc.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deparse.dpframe.ui.activity.DPBaseActivity;
import com.deparse.dpframe.ui.activity.DPBaseActivityWithSimpleActionBar;
import com.deparse.dpframe.utils.DPCommonUtil;
import com.deparse.dpframe.utils.DPFileUtil;
import com.deparse.dpframe.utils.DPLogUtil;
import com.deparse.dpframe.utils.DPUnitUtil;
import com.hsy.bibc.common.Config;
import com.hsy.bibc.common.Consts;
import com.hsy.bibc.modules.common.CommonBaseActivityWithSimpleActionBar;
import com.hsy.bibc.modules.login.LoginActivity;
import com.hsy.bibc.R;
import com.hsy.bibc.modules.main.MainActivity;

import java.util.ArrayList;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by hsy on 2016/3/23.
 */
public class CommonUtils {
    public static final int TYPE_FROM_CAMERA = 0;
    public static final int TYPE_FROM_ALBUM = 1;
    private static final String INVALID_IM_TOKEN = "INVALID_IM_TOKEN#$@#@%$@!#^#@!#!#%@#$@!#%INVALID_IM_TOKEN";
    private static final String INVALID_IM_ID = "INVALID_IM_ID#$@#@%$@!#^#@!#!#%@#$@!#%INVALID_IM_ID";
    public static String INVALID_TOKEN = "-1";

    public static final String INVALID_UID = "INVALID_UID";
    private static String mUid = INVALID_UID;
    private static String isFp = "-1";
    private static String isDh = "-1";
    private static String isXf = "-1";


    public static void saveUserId(Context context, String userId) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_ID, userId).commit();
    }

    public static String getUserId(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_USER_ID, "-1");
    }

    public static void saveUserName(Context context, String userName) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_NAME, userName).commit();
    }

    public static void saveUserPhone(Context context, String userPhone) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_PHONE, userPhone).commit();
    }

    public static void saveUserTel(Context context, String userTel) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_TEL, userTel).commit();
    }

    public static void saveUserFP(Context context, String is_fp) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_FP, is_fp).commit();
    }

    public static String getUserFP(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_USER_FP, isFp);
    }

    public static void saveUserDH(Context context, String is_dh) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_DH, is_dh).commit();
    }

    public static String getUserDH(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_USER_DH, isDh);
    }

    public static void saveUserXf(Context context, String is_xf) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_XF, is_xf).commit();
    }

    public static String getUserXf(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_USER_XF, isXf);
    }

    public static void saveUserMap(Context context, String map) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_MAP, map).commit();
    }

    public static void saveUserAddress(Context context, String address) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_ADDRESS, address).commit();
    }

    public static void saveUserLogo(Context context, String logo) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_USER_LOGO, logo).commit();
    }


    public static void saveToken(Context context, String token) {
        CommonUtils.setUid(context, token);
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_TOKEN, token).commit();
    }

    public static String getToken(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_TOKEN, INVALID_TOKEN);
    }

    public static void clearToken(Context context) {
        CommonUtils.clearUid(context);
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().remove(Consts.KEY_TOKEN).commit();
    }

    public static void saveImToken(Context context, String imtoken) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_IM_TOKEN, imtoken).commit();
    }

    public static String getImToken(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_IM_TOKEN, INVALID_IM_TOKEN);
    }

    public static void clearImToken(Context context) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().remove(Consts.KEY_IM_TOKEN).commit();
    }

    public static void saveImId(Context context, String imid) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.KEY_IM_ID, imid).commit();
    }

    public static String getImId(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.KEY_IM_ID, INVALID_IM_ID);
    }

    public static void clearImId(Context context) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().remove(Consts.KEY_IM_ID).commit();
    }

    public static void setUid(Context context, String mUid) {
        CommonUtils.mUid = mUid;
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.UID, mUid).commit();
    }

    public static String getUid(Context context) {
        if (INVALID_UID.equals(CommonUtils.mUid)) {
            CommonUtils.mUid = context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.UID, INVALID_UID);
        }
        return CommonUtils.mUid;
    }

    public static void clearUid(Context context) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().remove(Consts.UID).commit();
    }

    public static void setContactsVersion(Context context, String v) {
        context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).edit().putString(Consts.CONTACTS_VERSION, v).commit();
    }

    public static String getContactsVersion(Context context) {
        return context.getSharedPreferences(Config.SHARED_PREFERENCES_NAME, Context.MODE_APPEND).getString(Consts.CONTACTS_VERSION, "0");
    }

    public static boolean checkLogin(Context context) {
        String token = getToken(context);
        if (INVALID_TOKEN.equals(token)) {
            return false;
        }
        return true;
    }

    private static ProgressDialog mProgressDialog = null;

    public static void showProgressDialog(Context context) {
//        DPLogUtil.printStackTrace("printStackTrace");
        if (null == mProgressDialog || !mProgressDialog.isShowing()) {
            mProgressDialog = new ProgressDialog(context);
            mProgressDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            mProgressDialog.setMessage("数据加载中，请稍后...");
            mProgressDialog.setIndeterminate(true);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
//                    HttpUtil.cancelRequest();
                }
            });
            mProgressDialog.show();
        }
    }

    public static void hideProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    private static Dialog imageSelectDialog;

    public static void showImageSelectDialog(@NonNull final DPBaseActivity activity, final ArrayList<String> defaultSelectedImages, final ImageSelectDialogDismissListener listener, final String isSingle) {
        View layout = View.inflate(activity, R.layout.image_select_dialog, null);
        layout.findViewById(R.id.from_camera).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == listener || !listener.onDismiss(TYPE_FROM_CAMERA)) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    activity.startActivityForResult(intent, Consts.REQ_TAKE_PICTURES);
                }
                if (null != imageSelectDialog) {
                    imageSelectDialog.dismiss();
                }
            }
        });
        layout.findViewById(R.id.from_album).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == listener || !listener.onDismiss(TYPE_FROM_ALBUM)) {
                    Intent intent = new Intent(activity, MultiImageSelectorActivity.class);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
                    if (null != isSingle || !isSingle.equals("")) {
                        DPLogUtil.d("isSingle=" + isSingle);
                        if ("true".equals(isSingle)) {
                            DPLogUtil.d("isSingle=" + isSingle);
                            intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
                        }
                    }

                    if (null != defaultSelectedImages) {
                        intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultSelectedImages);
                    }
                    activity.startActivityForResult(intent, Consts.REQ_SELECT_IMAGES);
                }
                if (null != imageSelectDialog) {
                    imageSelectDialog.dismiss();
                }
            }
        });
        imageSelectDialog = new Dialog(activity, R.style.image_select_dialog_style);
        imageSelectDialog.setContentView(layout);
        imageSelectDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                imageSelectDialog = null;
            }
        });
        imageSelectDialog.show();
    }

    public static String getImageCacheDir(Context context) {
        return DPFileUtil.getCacheDir(context, Consts.IMAGE_CACHE_DIR_NAME);
    }

    public static void showAuthFailureDialog(final Context activityContext, final String msg) {
        if (null != authDialog) {
            return;
        }

        hideProgressDialog();

        if (null != imageSelectDialog && imageSelectDialog.isShowing()) {
            imageSelectDialog.dismiss();
        }

        LinearLayout layout = new LinearLayout(activityContext);
        layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        TextView textView = new TextView(activityContext);
        textView.setText(msg);
        textView.setTextAppearance(activityContext, R.style.style_auth_err_msg);

        int padding = DPUnitUtil.dip2px(activityContext, 10);
        textView.setPadding(padding, padding, padding, padding);

        layout.addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        final AlertDialog.Builder builder = new AlertDialog.Builder(activityContext);
        builder.setView(layout);
        builder.setPositiveButton(R.string.txt_confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        activityContext.startActivity(new Intent(activityContext, LoginActivity.class));
                    }
                });

        authDialog = builder.create();
        authDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                handler.removeCallbacks(runnable);
                authDialog = null;
                activityContext.startActivity(new Intent(activityContext, LoginActivity.class));
            }
        });
        authDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        authDialog.show();

        handler.postDelayed(runnable, 5000);
    }

    public static void showErrorMsgDialog(final Context activityContext, final String msg) {

        hideProgressDialog();

        LinearLayout layout = new LinearLayout(activityContext);
        layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        TextView textView = new TextView(activityContext);
        textView.setText(msg);
        textView.setTextAppearance(activityContext, R.style.style_auth_err_msg);

        int padding = DPUnitUtil.dip2px(activityContext, 10);
        textView.setPadding(padding, padding, padding, padding);

        layout.addView(textView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        final AlertDialog.Builder builder = new AlertDialog.Builder(activityContext);
        builder.setView(layout);
        builder.setPositiveButton(R.string.txt_confirm,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        if (null != errorDialog) {
                            errorDialog.dismiss();
                            errorDialog = null;
                        }
                        ((CommonBaseActivityWithSimpleActionBar) activityContext).startActivityWithTaskCleared(MainActivity.class);
                    }
                });

        errorDialog = builder.create();
        errorDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                handler.removeCallbacks(errorRunnable);
                errorDialog = null;
                ((CommonBaseActivityWithSimpleActionBar) activityContext).startActivityWithTaskCleared(MainActivity.class);
            }
        });
        errorDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        errorDialog.show();

        handler.postDelayed(errorRunnable, 5000);
    }


    private static AlertDialog authDialog, errorDialog;

    private static Handler handler = new Handler();
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (null != authDialog) {
                authDialog.dismiss();
                authDialog = null;
            }
        }
    };
    private static Runnable errorRunnable = new Runnable() {
        @Override
        public void run() {
            if (null != errorDialog) {
                errorDialog.dismiss();
                errorDialog = null;
            }
        }
    };

    public static void showUploadProgressDialog(Context context) {
        DPCommonUtil.showUploadProgressDialog(context, "");
    }

    public static void hideUploadProgressDialog() {
        DPCommonUtil.hideUploadProgressDialog();
    }

    public static String getIsFp(Context context) {
        isFp = getUserFP(context);
        return isFp;
    }

    public static String getIsDh(Context context) {
        isDh = getUserDH(context);
        return isDh;
    }

    public static String getIsXf(Context context) {
        isXf = getUserXf(context);
        return isXf;

    }

    public interface ImageSelectDialogDismissListener {
        boolean onDismiss(int type);
    }

    public interface IDetailActionBarInitListener {
        void onInit(ImageView shareButton, ImageView collectButton, TextView collectNumTextView);
    }

    public static void showDetailActionBar(final DPBaseActivityWithSimpleActionBar activity, final IDetailActionBarInitListener onDetailActionBarInitListener, final View.OnClickListener shareOnClickListener, final View.OnClickListener collectOnClickListener) {
        RelativeLayout headContainer = (RelativeLayout) activity.getActionBarContainer();
        final View view = LayoutInflater.from(activity).inflate(R.layout.share_and_collect_buttons_layout, null);
        RelativeLayout.LayoutParams collectNumParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        collectNumParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        collectNumParams.addRule(RelativeLayout.CENTER_VERTICAL);
        headContainer.addView(view, collectNumParams);

        final View collectContainer = view.findViewById(R.id.collect_container);
        final ImageButton shareButton = (ImageButton) view.findViewById(R.id.share_button);
        final ImageButton collectButton = (ImageButton) view.findViewById(R.id.collect_button);
        final TextView collectNum = (TextView) view.findViewById(R.id.collect_num);

        if (null != onDetailActionBarInitListener) {
            onDetailActionBarInitListener.onInit(shareButton, collectButton, collectNum);
        }

        if (null != shareOnClickListener) {
            shareButton.setOnClickListener(shareOnClickListener);
        }

        if (null != collectOnClickListener) {
            collectButton.setOnClickListener(collectOnClickListener);
            collectContainer.setOnClickListener(collectOnClickListener);
        }
    }

    public static void setPricePoint(final EditText editText) {
        editText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                if (s.toString().contains(".")) {
//                    if (s.toString().trim().substring(0).equals(".")) {
//                        s = "0" + s;
//                        editText.setText("0.");
//                        editText.setSelection(2);
//                    } else
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editText.setText(s);
                        editText.setSelection(s.length());
                    }
                }


                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editText.setText(s.subSequence(0, 1));
                        editText.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });

    }
}
